package com.horizon.common.repository;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页查询数据封装
 *
 * @author wangfuwei
 * @version 2018-08-07
 */
@Getter
@Setter
public class Page<T> {

    /**
     * 默认每页条数
     */
    public static final Integer DEFAULT_ROWSIZE = 10;

    /**
     * 默认显示页码最大数
     */
    public static final Integer DEFAULT_PAGESIZE = 10;

    /**
     * 明细数据
     */
    private List<T> list;

    {
        list = new ArrayList<>();
    }

    /**
     * 当前页码
     */
    private Integer pageno = 1;

    /**
     * 每页条数
     */
    private Integer rowsize = DEFAULT_ROWSIZE;

    /**
     * 总页码
     */
    private Integer total = 1;

    /**
     * 总条数
     */
    private Integer totalrows = 0;

    /**
     * 当前页数据起始索引(从0开始)
     */
    private Integer start;

    /**
     * 当前页数据结束索引(从0开始)
     */
    private Integer end;

    /**
     * 所有页码
     */
    private ArrayList<Integer> pagingList = new ArrayList<>();

    /**
     * 开始页码
     */
    private Integer startPagingNo = 1;

    /**
     * 结束页码
     */
    private Integer endPagingNo = 0;

    /**
     * 初始化空页面
     */
    void getEmptyPage() {
        this.setRowsize(DEFAULT_ROWSIZE);
        this.getList().clear();
        this.getPagingList().clear();
        this.setTotal(1);
        this.setPageno(1);
    }

    /**
     * 运算分页逻辑
     */
    void excecute() {
        if (this.pageno <= 0)
            this.pageno = 1;
        if (this.rowsize <= 0)
            this.rowsize = DEFAULT_ROWSIZE;
        Integer start;

        if (this.totalrows <= (this.pageno - 1) * this.rowsize)
            if (this.totalrows % this.rowsize == 0)
                this.pageno = (this.totalrows / this.rowsize);
            else
                this.pageno = (this.totalrows / this.rowsize + 1);

        if (this.pageno <= 0)
            this.pageno = 1;
        start = this.rowsize * (this.pageno - 1);
        Integer totalpage;

        if (this.totalrows % this.rowsize == 0)
            totalpage = this.totalrows / this.rowsize;
        else
            totalpage = this.totalrows / this.rowsize + 1;

        this.total = totalpage;
        this.start = start;

        this.end = (start + this.rowsize - 1);
        if (this.end > this.totalrows) {
            this.end = this.totalrows;
        }

        if (this.total < DEFAULT_PAGESIZE)
            this.endPagingNo = this.total;
        else
            this.endPagingNo = DEFAULT_PAGESIZE;

        this.pagingList.clear();
        for (Integer i = this.startPagingNo; i <= this.endPagingNo; ++i) this.pagingList.add(i);
    }

    /**
     * 是否存在下一页
     */
    public Boolean hasNextPage() {
        return (this.pageno < this.total);
    }

    /**
     * 是否存在上一页
     */
    public Boolean hasPrePage() {
        return (this.pageno > 1);
    }
}